package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constants.RedisConstants;
import com.hmdp.constants.SystemConstants;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SendMailUtil;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.RedisConstants.USER_SIGN_KEY;


@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    private SendMailUtil sendMailUtils;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Result sendCode(String phone, HttpSession session) {

        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        // 3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        //发送验证码
//        sendMailUtils.sendCode(phone, code);
        log.debug("发送短信验证码成功，验证码：{}", code);

        // 4-1保存手机号和验证码到 session
//        session.setAttribute(phone, code);

        // 4-2保存手机号和验证码到 redis 5分钟有效
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        // 1.校验手机号
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //2-1验证码获取（session）
        //String cacheCode = session.getAttribute(phone).toString();

        //2-2验证码获取(redis)
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);

        // 3.校验手机号对应的验证码
        if (cacheCode == null || !cacheCode.equals(code)) {
            //3.不一致，报错
            return Result.fail("验证码错误");
        }

        //4.一致，根据手机号查询用户
        User user = this.query().eq("phone", phone).one();

        //5.判断用户是否存在
        if (user == null) {
            //不存在，则创建  =>注册用户
            user = createUserWithPhone(phone);
        }
        //7-1.保存用户信息到session中
        //session.setAttribute("user", user);

        // 7-2.随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        // 7-2.将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);


        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,
                //存在类型转换异常 Long不能转化为String 需自定义
                new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        // 7-2.存储
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
/*
        //使用string类型存储，需要手动序列化 string类型 不易修改 直观
        try {
            stringRedisTemplate.opsForValue().set(tokenKey,new ObjectMapper().writeValueAsString(userDTO));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }*/


        // 7-2.设置token有效期
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        return Result.ok(token);
    }

    @Override
    public Result visitUser(Long id) {
        // 查询详情
        User user = this.getById(id);
        if (user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }

    @Override
    public Result sign() {
        //1、获取用户信息
        Long id = UserHolder.getUser().getId();
        //2、获取日期
        String keySuffix = LocalDate.now().format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //3、拼接key
        String key = USER_SIGN_KEY + id + keySuffix;
        //4、获取日
        int dayOfMonth = LocalDate.now().getDayOfMonth(); //1-31
        //5、存入bitMap
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1、获取用户信息
        Long id = UserHolder.getUser().getId();
        //2、获取日期
        String keySuffix = LocalDate.now().format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //3、拼接key
        String key = USER_SIGN_KEY + id + keySuffix;
        //4、获取日
        int dayOfMonth = LocalDate.now().getDayOfMonth(); //1-31
        //5、从bitmap中读取截止今天的数据 返回的是一个十进制的数字 TODO bitfield key get u27 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create().get(
                        BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()) {
            // 没有任何签到结果
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        //6、循环遍历 统计连续签到次数
        int count = 0;
        while (true) {
            //获取最后一个数字
            if ((num & 1) == 0) {
                break;
            } else {
                count++;
            }
            // 把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            //TODO 3个>>>代表无符号位的右移 2个>>代表有符号位的右移
            num = num >>> 1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        //注册新用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        this.save(user);
        return user;
    }
}
